package com.tubang.component.component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.tubang.common.util.DateFormatUtils;
import com.tubang.common.util.StringUtils;

import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
@Component
@PropertySource("classpath:application.properties")
public class UploadUtils {
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Value("${tubang.upload.path}")
	private String realPath;
	
	public String uploadPic(MultipartFile file, HttpServletRequest request) {
		try {
			if (null != file) {
				String[] split = file.getOriginalFilename().split("\\.");
				String ext = split[split.length - 1];
				String filename = UUID.randomUUID().toString() + "." + ext;
				String path = "/images/" + DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
				String url = realPath + path + filename;
				logger.info("ext,{}======filename,{}=====path,{}=====url,{}");
				// 此图片保存到指定位置
				File dir = new File(realPath + path);
				logger.info("method[uploadPic] !dir.exists()--》{}============!dir.isDirectory()-->{}",!dir.exists(),!dir.isDirectory());
				if (!dir.exists() && !dir.isDirectory()) {
					logger.info("method[uploadPic]文件不存在，正在创建文件。。。。。");
					dir.mkdirs();
					logger.info("method[uploadPic]文件创建完成 success。。。。。。。");
				}
				file.transferTo(new File(url));
				return path + filename;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.error("上传文件失败：失败原因为：{}",e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * @fun 对字节数组字符串进行Base64解码后生成图片，并且保存到 realPath + path + filename;
	 * @param imgBase64Str
	 * @return 图片名
	 * @throws Exception
	 */
	public String uploadPicByBase64(String imgBase64Str, HttpServletRequest request)throws Exception {
		OutputStream out = null;
		// 图像数据为空
	    if (StringUtils.isBlank(imgBase64Str)) {
	        return null;
	    }
	    //对图片内容进行预处理
        imgBase64Str = imgBase64Str.replace("data:image/jpeg;base64,", "");
        imgBase64Str = imgBase64Str.replace(" ", "+").replace("\r\n", "");
        
		try {
	        //对图片内容BASE64解码，还原成图片
			BASE64Decoder decoder = new BASE64Decoder();
		    byte[] b = decoder.decodeBuffer(imgBase64Str);			
		    for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
			}
		    
		    String filename = UUID.randomUUID().toString() + ".jpg";
			String path = "/images/" + DateFormatUtils.format(new Date(), "yyyyMMdd") + "/";
			String url = realPath + path + filename;
		    
	        //判断文件夹是否存在，如果不存在则创建        
	        File dir = new File(realPath + path);
	        if (!dir.exists() && !dir.isDirectory()) {
	        	dir.mkdirs();
	        }
	        //生成jpg图片,最终图片写的位置
	        out = new FileOutputStream(url);
	        out.write(b);
	        out.flush();
	        return path + filename;
        } catch (Exception e) {
            logger.error("fileName Exception: " + e.getMessage(), e);
            return null;
        } finally {
            try {
                out.close();
            } catch (Exception ex) {
                logger.error("close the file failed:" + ex.getMessage(), ex);
            }
        }
	}

	/**
	 * @功能描述 删除文件
	 * @author
	 */
	public Boolean deleteFile(String url){
		boolean flag=false;
			//本地测试使用
            File dir=new File("D:/upload/"+url);
            if (dir.isFile() && dir.exists()) {  
            	dir.delete();  
            	flag=true;
            }  
            return flag;
	}
}
